package com.example.wxback.push;

import com.example.wxback.model.PushResultInfo;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.BufferedReader;
import java.io.InputStreamReader;


public class PushClient {

    private Logger log = LogManager.getLogger(PushClient.class);

    // The user agent
    protected final String USER_AGENT = "Mozilla/5.0";
    // This object is used for sending the post request to Umeng
    protected HttpClient client = new DefaultHttpClient();

    public PushResultInfo send(String url, String postBody, String appIOSMasterSecret) throws Exception {
        String sign = DigestUtils.md5Hex(("POST" + url + postBody + appIOSMasterSecret).getBytes("utf8"));
        url = url + "?sign=" + sign;
        HttpPost post = new HttpPost(url);
        post.setHeader("User-Agent", USER_AGENT);
        StringEntity se = new StringEntity(postBody, "UTF-8");
        post.setEntity(se);
        // Send the post request and get the response
        HttpResponse response = client.execute(post);
        int status = response.getStatusLine().getStatusCode();
        log.debug(String.format("Response Code : %s", status));
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        PushResultInfo pushResultInfo = new PushResultInfo();
        pushResultInfo.setContent(result.toString());
        System.out.println(result.toString());
        if (status == 200) {
            log.debug("success");
            pushResultInfo.setSuccess(true);
        } else {
            log.debug("fail");
            pushResultInfo.setSuccess(false);
        }
        return pushResultInfo;
    }
}